<template>
  <div>
    <el-card class="box-card">
      <h2>分配合同</h2>
      <el-form :model="assignForm" label-width="120px">
        <el-form-item label="合同名称：">
          <el-input v-model="assignForm.contractName" readonly></el-input>
        </el-form-item>

        <!-- 会签人 -->
        <el-row :gutter="20" class="user-selection">
          <el-col :span="11">
            <el-card>
              <h3>会签人</h3>
              <el-select v-model="selectedCountersignUser" placeholder="选择会签人" style="width: 100%;">
                <el-option v-for="user in availableCountersignUsers" :key="user.id" :label="user.username" :value="user.id"></el-option>
              </el-select>
              <el-button @click="addCountersignUser" type="primary" style="margin-top: 10px;">添加</el-button>
            </el-card>
          </el-col>
          <el-col :span="11">
            <el-card>
              <h3>已选会签人</h3>
              <div class="selected-users">
                <el-tag
                  v-for="user in assignForm.countersignUsers"
                  :key="user"
                  closable
                  @close="removeCountersignUser(user)"
                >
                  {{ getUserById(user).username }}
                </el-tag>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 审批人 -->
        <el-row :gutter="20" class="user-selection">
          <el-col :span="11">
            <el-card>
              <h3>审批人</h3>
              <el-select v-model="selectedApprovalUser" placeholder="选择审批人" style="width: 100%;">
                <el-option v-for="user in availableApprovalUsers" :key="user.id" :label="user.username" :value="user.id"></el-option>
              </el-select>
              <el-button @click="addApprovalUser" type="primary" style="margin-top: 10px;">添加</el-button>
            </el-card>
          </el-col>
          <el-col :span="11">
            <el-card>
              <h3>已选审批人</h3>
              <div class="selected-users">
                <el-tag
                  v-for="user in assignForm.approvalUsers"
                  :key="user"
                  closable
                  @close="removeApprovalUser(user)"
                >
                  {{ getUserById(user).username }}
                </el-tag>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 签订人 -->
        <el-row :gutter="20" class="user-selection">
          <el-col :span="11">
            <el-card>
              <h3>签订人</h3>
              <el-select v-model="selectedSigningUser" placeholder="选择签订人" style="width: 100%;">
                <el-option v-for="user in availableSigningUsers" :key="user.id" :label="user.username" :value="user.id"></el-option>
              </el-select>
              <el-button @click="addSigningUser" type="primary" style="margin-top: 10px;">添加</el-button>
            </el-card>
          </el-col>
          <el-col :span="11">
            <el-card>
              <h3>已选签订人</h3>
              <div class="selected-users">
                <el-tag
                  v-for="user in assignForm.signingUsers"
                  :key="user"
                  closable
                  @close="removeSigningUser(user)"
                >
                  {{ getUserById(user).username }}
                </el-tag>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm">完成分配</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      assignForm: {
        contractName: this.$route.params.contractName,
        countersignUsers: [],
        approvalUsers: [],
        signingUsers: [],
      },
      users: [],
      selectedCountersignUser: '',
      selectedApprovalUser: '',
      selectedSigningUser: '',
    };
  },
  computed: {
    availableCountersignUsers() {
      return this.users.filter(user => !this.assignForm.countersignUsers.includes(user.id));
    },
    availableApprovalUsers() {
      return this.users.filter(user => !this.assignForm.approvalUsers.includes(user.id));
    },
    availableSigningUsers() {
      return this.users.filter(user => !this.assignForm.signingUsers.includes(user.id));
    },
  },
  created() {
    this.fetchUsers();
    this.fetchContractDetails(this.$route.params.contractName);
  },
  methods: {
    fetchUsers() {
      this.axios.get('/api/user/get')
        .then(response => {
          this.users = response.data.data;
        })
        .catch(error => {
          console.error('Error fetching users:', error);
          this.$message.error('获取用户列表失败');
        });
    },
    fetchContractDetails(contractName) {
      this.axios.get(`/api/contract/name/${contractName}`)
        .then(response => {
          const contract = response.data.data;
          this.assignForm.contractName = contract.name;
        })
        .catch(error => {
          console.error('Error fetching contract details:', error);
          this.$message.error('获取合同详情失败');
        });
    },
    getUserById(id) {
      return this.users.find(user => user.id === id) || {};
    },
    addCountersignUser() {
      if (this.selectedCountersignUser && !this.assignForm.countersignUsers.includes(this.selectedCountersignUser)) {
        this.assignForm.countersignUsers.push(this.selectedCountersignUser);
        this.selectedCountersignUser = '';
      }
    },
    removeCountersignUser(user) {
      const index = this.assignForm.countersignUsers.indexOf(user);
      if (index > -1) {
        this.assignForm.countersignUsers.splice(index, 1);
      }
    },
    addApprovalUser() {
      if (this.selectedApprovalUser && !this.assignForm.approvalUsers.includes(this.selectedApprovalUser)) {
        this.assignForm.approvalUsers.push(this.selectedApprovalUser);
        this.selectedApprovalUser = '';
      }
    },
    removeApprovalUser(user) {
      const index = this.assignForm.approvalUsers.indexOf(user);
      if (index > -1) {
        this.assignForm.approvalUsers.splice(index, 1);
      }
    },
    addSigningUser() {
      if (this.selectedSigningUser && !this.assignForm.signingUsers.includes(this.selectedSigningUser)) {
        this.assignForm.signingUsers.push(this.selectedSigningUser);
        this.selectedSigningUser = '';
      }
    },
    removeSigningUser(user) {
      const index = this.assignForm.signingUsers.indexOf(user);
      if (index > -1) {
        this.assignForm.signingUsers.splice(index, 1);
      }
    },
    submitForm() {
      const url = `/api/contract/${this.assignForm.contractName}/assign`;
      this.axios.post(url, {
        countersignUsers: this.assignForm.countersignUsers,
        approvalUsers: this.assignForm.approvalUsers,
        signingUsers: this.assignForm.signingUsers,
      })
        .then(() => {
          this.$message({
            message: '合同分配成功',
            type: 'success',
          });
          this.$router.push('/maininterface');
        })
        .catch(error => {
          console.error('Error assigning contract:', error);
          this.$message.error('合同分配失败');
        });
    },
    resetForm() {
      this.assignForm.countersignUsers = [];
      this.assignForm.approvalUsers = [];
      this.assignForm.signingUsers = [];
    },
  },
};
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 800px;
}
.el-form-item {
  margin-bottom: 20px;
}
.selected-users {
  display: flex;
  flex-wrap: wrap;
}
.user-selection {
  margin-bottom: 20px;
}
</style>
